import { Component, Input, OnInit, AfterViewInit, ViewChild, ElementRef, SimpleChanges } from "@angular/core";
import * as OriginChart from "chart.js";

// util
import { getId } from "utils";
// f1o util
import { chartColors } from "../util"

@Component({
  selector: 'doughnut',
  templateUrl: 'doughnut.component.html',
  styleUrls: ['doughnut.component.less'],
  inputs: ['data']
})
export class DoughnutComponent implements OnInit {
  @ViewChild("canvas", {read: ElementRef})
  canvasEl: ElementRef;
  data: any;
  chartInstance;
  config = {
    type: 'doughnut',
    data: {
      datasets: [{
        data: [],
        backgroundColor: [],
        label: '股本结构'
      }],
      labels: []
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: ''
      },
      animation: {
        animateScale: true,
        animateRotate: true
      }
    }
  }
  constructor () {}

  ngOnInit () {}

  ngOnChanges (changes: SimpleChanges) {
    if (changes.data && changes.data.currentValue) {
      this.renderChart(changes.data.currentValue)
    }
  }

  ngAfterViewInit() {
    let chart = this.canvasEl.nativeElement;
    this.chartInstance = new OriginChart(chart, this.config)
  }

  renderChart (config) {
    // change chart config
    this.config.data.datasets[0].data = [...config.data.datasets[0].data]
    this.config.data.datasets[0].backgroundColor = [...config.data.datasets[0].backgroundColor]
    this.config.data.labels = [...config.data.labels]
    this.config.options.legend.position = config.options.legend.position || 'top'
    this.config.options.title.text = config.options.title.text
    this.chartInstance.update()
  }
}